package cn.edu.ujn.multiple.controller;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ImageController
 */
@WebServlet("/ImageServlet")
public class ImageController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImageController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 生成验证码图片
		BufferedImage bImage = new BufferedImage(64, 22, BufferedImage.TYPE_INT_RGB);
		Graphics graphics = bImage.getGraphics();// 获取验证码图片
		Color color = new Color(255, 255, 255);// 给验证码设置为白色背景
		graphics.setColor(color);
		graphics.fillRect(0, 0, 68, 22);// 设置文字图片的位置
		char[] ch = "ASCDEFGHIJKLMNOPQRSTUVWXYZ0987654321".toCharArray();
		Random r = new Random();
		int len = ch.length, index;
		// 在空串中填充随机生成的验证码
		String s = "";
		for (int i = 0; i < 4; i++) {
			index = r.nextInt(len);
			graphics.setColor(new Color(r.nextInt(70), r.nextInt(180), r.nextInt(256)));
			graphics.drawString(ch[index] + "", (i * 15) + 5, 16);// 设置每个字符的位置
			s += ch[index];// 添加到空串
		}

		request.getSession().setAttribute("piccode", s);// 将验证码结果放到session中，以便验证对错
		ImageIO.write(bImage, "JPG", response.getOutputStream());// 输出图像到页面
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
